<template>
  <div class="app-container">
    <a-title @clickPreview="preview" />
    <el-row :gutter="20">
      <!--业务类别数据-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入业务类别名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="tree"
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span class="childrenNum">{{ data.childrenNum }}</span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="100px">
          <el-form-item label="目录模板名称" prop="templateName">
            <el-input
              v-model="queryParams.templateName"
              placeholder="请输入"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- <el-form-item label="更新人" prop="updateBy">
            <el-input
              v-model="queryParams.updateBy"
              placeholder="请输入更新人"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>-->
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              clearable
              size="small"
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择创建时间"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:docCatalogTemplate:add']"
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:docCatalogTemplate:edit']"
            >修改</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              v-hasPermi="['system:docCatalogTemplate:remove']"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              v-hasPermi="['system:docCatalogTemplate:export']"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              :disabled="multiple"
            >下载</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              v-hasPermi="['system:taskTemplate:export']"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExportTemplate"
            >下载模板文件</el-button>
          </el-col>
        </el-row>

        <el-table
          stripe
          v-loading="loading"
          :data="docCatalogTemplateList"
          @sort-change="tableSortChange"
          @selection-change="handleSelectionChange"
          :default-sort="{prop: 'createTime', order: 'descending'}"
        >
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="id 主键" align="center" prop="id" /> -->
          <el-table-column
            label="目录模板名称"
            align="left"
            prop="templateName"
            :sort-orders="['ascending', 'descending']"
            sortable="custom"
          />
          <el-table-column label="业务类别" align="center" prop="businessCategoryList">
            <template slot-scope="{row}">
              <div v-for="(item,index) in row.businessCategoryList" :key="index">{{ item.menuName }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :sort-orders="['ascending', 'descending']"
            sortable="custom"
          />
          <el-table-column
            label="模板文件"
            align="left"
            prop="attachmentList"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="{row}">{{ row.attachmentList[0].fileName }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handlePreview(scope.row)"
                icon="el-icon-search"
              >预览</el-button>
              <el-button
                v-hasPermi="['system:docCatalogTemplate:edit']"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >编辑</el-button>
              <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:docCatalogTemplate:remove']"
              >删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改项目文档目录模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="业务类别" prop="businessCategoryIds">
          <treeselect
            v-model="form.businessCategoryIds"
            :options="deptOptionsChild"
            placeholder="请选择业务类别"
            :disable-branch-nodes="true"
            :multiple="true"
          />
        </el-form-item>
        <el-form-item label="附件" prop="attachmentId">
          <vue-uploader
            v-if="open"
            :single-type="taskSingle"
            :file-list="form.attachmentList"
            @changeFileData="changeFile"
            @removeFileList="removeFileList"
            :pathName="'TJECdocuments/业务模板/项目文档目录'"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 预览 -->
    <el-dialog :visible.sync="openPreview" width="80%">
      <iframe :src="manualPreviewUrl" frameborder="0" width="100%" height="700px"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import aTitle from '@/components/Title';
import {
  listDocCatalogTemplate,
  getDocCatalogTemplate,
  delDocCatalogTemplate,
  addDocCatalogTemplate,
  updateDocCatalogTemplate,
  exportDocCatalogTemplate,
  fileType
} from '@/api/system/docCatalogTemplate';
import { systemMixin, treeSelectList } from '@/mixins/systemMixin.js';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import vueUploader from '@/components/Uploader';
import { handleBatchDownload } from '@/api/zipdownload';
export default {
  name: 'DocCatalogTemplate',
  components: {
    Treeselect,
    vueUploader,
    aTitle
  },
  mixins: [systemMixin, treeSelectList],
  data () {
    return {
      manualPreviewUrl: null,
      openPreview: false,
      pageTempName: 'DOC_CATALOG_TEMPLATE',
      taskSingle: true,
      // 遮罩层
      loading: true,
      // 选中数组
      guids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 项目文档目录模板表格数据
      docCatalogTemplateList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      // 新增部门树选项
      deptOptionsChild: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: undefined,
        updateBy: undefined,
        updateTime: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      files: [],
      allfiles: [],
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: '模板名称不能为空', trigger: 'blur' }
        ],
        attachmentId: [
          { required: true, message: '附件不能为空', trigger: 'blur' }
        ],
        businessCategoryIds: [
          { required: true, message: '业务类别不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName (val) {
      this.$refs.tree.filter(val)
    }
  },
  created () {
    this.getList()
    this.getTreeselect(this.pageTempName)
    this.getTreeSelectChild(this.pageTempName)
  },
  methods: {
    preview () {
      this.openPreview = true;
      this.manualPreviewUrl = `${this.previewUrl}${encodeURIComponent(
        `${this.operationManual}业务标准库/项目文档目录.xlsx`
      )}&name=${encodeURIComponent("项目文档目录.xlsx")}`;
    },
    /** 查询项目文档目录模板列表 */
    getList () {
      this.loading = true
      listDocCatalogTemplate(this.queryParams).then(response => {
        this.docCatalogTemplateList = response.rows
        response.rows.map(item => {
          this.allfiles.push({
            fileid: item.attachmentId,
            fileName: item.fileName
          })
        })
        this.total = response.total
        this.loading = false
      })
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true
      if (data.label != null) {
        return data.label.indexOf(value) !== -1
      }
    },
    // 节点单击事件
    handleNodeClick (data) {
      this.queryParams.businessCategoryId = data.id
      this.getList()
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        guid: undefined,
        templateName: undefined,
        attachmentId: undefined,
        businessCategoryIds: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.files = selection
      this.guids = selection.map(item => item.guid)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    tableSortChange (column) {
      this.queryParams.pageNum = 1;
      if (column.order === "descending") {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "desc";
      } else {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "asc";
      }
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      this.open = true
      this.title = '添加项目文档目录模板';
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      const guid = row.guid || this.guids
      getDocCatalogTemplate(guid).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改项目文档目录模板';
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      fileType({ guid: this.form.attachmentId }).then(res => {
        if (res.code === 200) {
          this.$refs['form'].validate(valid => {
            if (valid) {
              if (this.form.guid != undefined) {
                updateDocCatalogTemplate(this.form).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess('修改成功')
                    this.open = false
                    this.getList()
                    this.getTreeselect(this.pageTempName)
                    this.getTreeSelectChild(this.pageTempName)
                  } else {
                    this.msgError(response.msg)
                  }
                })
              } else {
                addDocCatalogTemplate(this.form).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess('新增成功')
                    this.open = false
                    this.getList()
                    this.getTreeselect(this.pageTempName)
                    this.getTreeSelectChild(this.pageTempName)
                  } else {
                    this.msgError(response.msg)
                  }
                })
              }
            }
          })
        } else if (res.code === 500) {
          this.msgError(res.msg)
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const guids = row.guid || this.guids
      this.$confirm('是否确认删除所有业务类别下的此项目文档模板? 如只删除该业务类别，请通过“修改”功能操作?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function () {
          return delDocCatalogTemplate(guids)
        })
        .then(() => {
          this.getList()
          this.getTreeselect(this.pageTempName)
          this.getTreeSelectChild(this.pageTempName)
          this.msgSuccess('删除成功')
        })
        .catch(function () { })
    },
    /** 导出按钮操作 */
    handleExport () {
      // const queryParams = this.queryParams;
      // this.$confirm("是否确认导出所有项目文档目录模板数据项?", "警告", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // })
      //   .then(function () {
      //     return exportDocCatalogTemplate(queryParams);
      //   })
      //   .then(response => {
      //     this.download(response.msg);
      //   })
      //   .catch(function () { });
      const filesList = []
      if (this.files.length === 0) {
        this.allfiles.map(item => {
          filesList.push({
            fileurl: '/api/system/download/' + item.fileid,
            fileName: item.fileName
          })
        })
        handleBatchDownload(filesList)
      } else {
        this.files.map(item => {
          filesList.push({
            fileurl: '/api/system/download/' + item.attachmentId,
            fileName: item.attachmentList[0].fileName
          })
        })
        handleBatchDownload(filesList)
      }
    },
    // 附件操作

    changeFile (id, name) {
      this.form.attachmentId = id
      this.form.attachmentList = []
      // this.$set(this.form, 'attachmentList', [{ fileName: name, guid: id }])
    },
    removeFileList (id) {
      this.form.attachmentId = null
      this.form.attachmentList = []
    },
    handlePreview (item) {
      const storagePath = item.attachmentList[0].storagePath
      const fileName = item.attachmentList[0].fileName
      this.filePreview(fileName, storagePath)
    }
  }
}
</script>
<style lang="scss" scoped>
.custom-tree-node {
  display: flex;
  flex: 1;
  .childrenNum {
    //flex: 1;
    text-align: right;
  }
}
</style>
